package com.linkage.seapeak.activity.message;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.pojo.CrediterNewUser;
import com.linkage.seapeak.pojo.CrediterUser;
import com.linkage.seapeak.utils.ToastUtil;
import com.seapeak.recyclebundle.BaseHolder;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 发送群聊消息 第二步 编辑内容
 */
public class MultiSendActivity extends BaseWhiteActivity {

    List<CrediterNewUser> userList;
    String targetIds = "";

//    private RecyclerView recyclerAvatar;
    private ImageView add;
    private TextView names_view;
    private EditText messageContent;
    private TextView textSum;

    String projectId;

    BaseRecyclerAdapter<ViewHolder> adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multi_send);
        initView();
    }

    private void initView() {
        userList = (List<CrediterNewUser>) getIntent().getSerializableExtra("userList");
        projectId = getIntent().getStringExtra("projectId");

//        recyclerAvatar = (RecyclerView) findViewById(R.id.recycler_avatar);
        add = (ImageView) findViewById(R.id.add);
        messageContent = (EditText) findViewById(R.id.message_content);
        names_view = (TextView) findViewById(R.id.names_view);
        textSum = (TextView) findViewById(R.id.text_sum);

        messageContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int sum = messageContent.length();
                if (sum > 300) {
                    messageContent.setText(messageContent.getText().toString().substring(0, 300));
                    sum = 300;
                }
                textSum.setText(sum + "/300");
            }
        });

        String userNameStr = "";
        for (int i = 0;i < userList.size();i++) {
            if (i > 3) {
                userNameStr += "等" + userList.size() + "人";
                break;
            }
            CrediterNewUser user = userList.get(i);
            if (i != 0)
                userNameStr += "，";
            userNameStr += user.getCreditorname();
        }

        names_view.setText(userNameStr);
//        recyclerAvatar.setLayoutManager(new LinearLayoutManager(MultiSendActivity.this,
//                LinearLayoutManager.HORIZONTAL, false));
//        adapter = new BaseRecyclerAdapter<ViewHolder>() {
//            @NonNull
//            @Override
//            public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
//                return new ViewHolder(LayoutInflater.from(MultiSendActivity.this)
//                        .inflate(R.layout.item_only_avatar, viewGroup, false));
//            }
//
//            @Override
//            public void onBindViewHolder(ViewHolder holder, int position) {
//                super.onBindViewHolder(holder, position);
//                CrediterUser user = userList.get(position);
//                if (user != null) {
//                    Glide.with(MultiSendActivity.this).load(user.getAvatar())
//                            .bitmapTransform(new CropCircleTransformation(MultiSendActivity.this))
//                            .placeholder(R.drawable.avatar_defult)
//                            .into(holder.avatar);
//                }
//            }
//
//            @Override
//            public int getItemCount() {
//                return userList.size();
//            }
//        };
//        recyclerAvatar.setAdapter(adapter);
        addMenu(new MenuAction(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendGroupMsg();
            }
        }, "完成", 0));

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MultiSelectActivity.start(MultiSendActivity.this, projectId);
                finish();
            }
        });
    }

    class ViewHolder extends BaseHolder {

        ImageView avatar;

        public ViewHolder(View view) {
            super(view);
            avatar = view.findViewById(R.id.img_avatar);
        }
    }

    public void sendGroupMsg() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }

        String contentStr = messageContent.getText().toString();
        if (TextUtils.isEmpty(contentStr)) {
            showToast("内容不可以为空");
            return;
        }

        for (CrediterNewUser item : userList)
            targetIds += "," + item.getSysUserId();
        if (!TextUtils.isEmpty(targetIds))
            targetIds = targetIds.substring(1);

        Network.getAPIService()
                .sendGroupMsg(getUserToken(), projectId, contentStr, targetIds)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            showToast(json.get("msg").getAsString());
                            return;
                        } else {
                            showToast("发送成功", ToastUtil.TOAST_TYPE.SUCCESS);
                            MultiMessageHistoryActivity.start(MultiSendActivity.this, projectId);
                            finish();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }
}
